package com.crb.crm.manage.message.dingding;

import com.crb.crm.manage.dao.biz.SystemConfigInfoMapper;
import com.crb.crm.manage.entity.biz.SystemConfigDTO;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Package: com.crb.crm.manage.message.dingding
 * Description： 钉钉推送以及授權工具
 * Author: huangjian
 * Modified By:
 */
@Component
public class DingDingTools {

    @Autowired
    private SystemConfigInfoMapper systemConfigInfoMapper;

    /**
     * 發送釘釘消息
     * @param taobaoObject
     * @param at
     * @return
     * @throws ApiException
     */
    public OapiRobotSendResponse sendMsg(TaobaoObject taobaoObject,
                                         OapiRobotSendRequest.At at) throws ApiException {
        SystemConfigDTO systemConfigDTO = systemConfigInfoMapper.getOneSystemConfigByCode("dingding_robot_send_hook");
        if(Objects.isNull(systemConfigDTO)|| StringUtils.isBlank(systemConfigDTO.getContent())){
            throw new IllegalArgumentException("配置项为空");
        }
        DingTalkClient client = new DefaultDingTalkClient(systemConfigDTO.getContent());
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        if(taobaoObject instanceof OapiRobotSendRequest.Text){
            request.setMsgtype("text");
            request.setText((OapiRobotSendRequest.Text) taobaoObject);
        } if(taobaoObject instanceof OapiRobotSendRequest.Link){
            request.setMsgtype("link");
            request.setLink((OapiRobotSendRequest.Link) taobaoObject);
        } if(taobaoObject instanceof OapiRobotSendRequest.Markdown){
            request.setMsgtype("markdown");
            request.setMarkdown((OapiRobotSendRequest.Markdown) taobaoObject);
        }
        if(!Objects.isNull(at)){
            request.setAt(at);
        }
        OapiRobotSendResponse response = client.execute(request);
        return response;
    }

}
